import Vuex from 'vuex'
export default function initModal(v) {
	// 挂在store到全局Vue原型上
	v.prototype.$modalStore = new Vuex.Store({
		state: {
			show: false,
			title: "提示",
			content: '',
			rich: false,
			tips: '',
			icon: null,
			showCancel: true,
			cancelText: "取消",
			cancelColor: "rgba(255,255,255,0.7)",
			cancelBackgroundColor: "#2F2F2F",
			confirmText: "确定",
			confirmColor: "#FFFFFF",
			confirmBackgroundColor: "#2F2F2F",
			success: null,
			vm: null,
			ref: 'showModal',
		},
		mutations: {
			hideModal(state) {
				// 小程序导航条页面控制
				// #ifndef H5
				if (state.hideTabBar) {
					wx.showTabBar();
				}
				// #endif
				state.show = false
			},
			showModal(state, data) {
				//判断页面是否加载组件
				// let vm = data.vm  
				// console.log('加载自定义弹窗组件',data,vm,vm.$refs,vm.$refs.showModal)
				let currentpage = getCurrentPages()
				var vm = currentpage[currentpage.length -1 ].$vm
				
				if (vm &&vm.$refs && vm.$refs[state.ref]) {
					state = Object.assign(state, data)
					console.log('弹窗参数',state);
					state.show = true
				}else{
					for(let item in data){
						state[item] = data[item]
					}
					//页面没有弹窗组件则调用系统弹窗
					uni.showModal({
						title:state.title,
						content:state.content,
						showCancel:state.showCancel,
						cancelText:state.cancelText,
						confirmText:state.confirmText,
						success:state.success,
					})
				}
			},
			success(state, res) {
				console.log('confirm:',state,res)
				let cb = state.success
				let resObj = { 
					cancel: false,
					confirm: false
				}
				res == "confirm" ? resObj.confirm = true : resObj.cancel = true
				cb && cb(resObj)
				//清空配置信息
				console.log('弹窗配置重置')
				state.title = '提示'
				state.icon = null
				state.content = ''
				state.tips = ''
				state.showCancel = true
				state.cancelText = '取消'
				state.confirmText = '确定'
				state.icon = null,
				state.success = null,
				state.rich = false
				state.ref = 'showModal'
			}
		}
	})
	v.prototype.$showModal = function(option) {
		if (typeof option === 'object') {
			// #ifndef H5
			if (option.hideTabBar) {
				wx.hideTabBar();
			}
			// #endif

			v.prototype.$modalStore.commit('showModal', option)
		} else {
			throw "配置项必须为对象传入的值为：" + typeof option;
		}
	}
}
